package com.gin.kotlin.no_gay_alliance.adapter.vote

import android.content.Context
import android.content.DialogInterface
import android.text.InputType
import android.util.Log
import android.view.View
import android.widget.EditText
import com.gin.kotlin.no_gay_alliance.app.App
import com.gin.kotlin.no_gay_alliance.base.AbstractBindingRecyclerViewAdapter
import com.gin.kotlin.no_gay_alliance.base.AlertDialogUtils
import com.gin.kotlin.no_gay_alliance.base.InputMethodUtils
import com.gin.kotlin.no_gay_alliance.base.IntRangeTextWatcher
import com.gin.kotlin.no_gay_alliance.base.MyHandler
import com.gin.kotlin.no_gay_alliance.databinding.ItemOptionBetBinding
import com.gin.nga.callback.NgaCallback
import com.gin.nga.response.base.NgaResponse
import com.gin.nga.response.vote.VoteOption
import retrofit2.Call
import retrofit2.Response
import java.time.ZonedDateTime
import java.util.Locale

/**
 * 菠菜适配器
 * @property successId 胜出的选项
 * @constructor
 */
class VoteBetAdapter(context: Context, handler: MyHandler, data: List<VoteOption> = mutableListOf()) :
    AbstractBindingRecyclerViewAdapter<ItemOptionBetBinding, VoteOption>(context, handler, true, data.toMutableList()), View.OnClickListener {
    var end: ZonedDateTime? = null
    var min: Int? = null
    var max: Int? = null
    var topicId: Long = 0
    var successId: Int? = null

    override fun onBindViewHolder(holder: ViewHolder<ItemOptionBetBinding>, position: Int, b: ItemOptionBetBinding, dataModel: VoteOption) {
        // 总人数
        val moneyPer = String.format(Locale.CHINESE, "%.2f", 100.0 * dataModel.moneyPer)
        b.tvCount.text = "${dataModel.money}铜 (${moneyPer}%)"

        // 进度条，铜币数
        b.progressBar.max = data.sumOf { it.money }
        b.progressBar.setProgress(dataModel.money, true)

        // 参与人数
        val countPer = String.format(Locale.CHINESE, "%.2f", 100.0 * dataModel.countPer)
        b.tvTitle.text = "${dataModel.label}, ${dataModel.count} 人(${countPer}%)"

        b.tvTagWin.visibility = if (successId != null && successId == dataModel.id) View.VISIBLE else View.GONE

        b.root.tag = dataModel
        b.root.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        val option = v?.tag as? VoteOption ?: return

        if (end!=null && ZonedDateTime.now().isAfter(end)){
            handler.toast("截止时间已过")
            return
        }

        Log.i(TAG, "onClick: ${option.label}")
        // 弹窗选择

        val editText = EditText(context)
        editText.inputType = InputType.TYPE_CLASS_NUMBER
        editText.addTextChangedListener(IntRangeTextWatcher(editText, min, max))
        editText.setText(min?.toString())
        editText.requestFocus()
        editText.setSelection(0)

        AlertDialogUtils.builder(
            context,
            title = "投注",
            message = "你选择了 ${option.label}",
            contentView = editText,
            listener = { _, which ->
                if (which == DialogInterface.BUTTON_POSITIVE) {
                    //投注
                    val money = editText.text.toString().toInt()

                    App.INSTANCE.ngaApi.topicReadApi.vote(topicId, listOf(option.id, money)).enqueue(object : NgaCallback<List<String>> {
                        override fun onSuccess(
                            call: Call<NgaResponse<List<String>>>,
                            response: Response<NgaResponse<List<String>>>,
                            body: NgaResponse<List<String>>?,
                            data: List<String>?
                        ) {
                            data?.get(0)?.also { handler.toast(it) }
                        }

                        override fun onError(
                            call: Call<NgaResponse<List<String>>>,
                            response: Response<NgaResponse<List<String>>>,
                            body: NgaResponse<List<String>>?,
                            errorMessage: String
                        ) {
                            handler.toastLong(errorMessage)
                        }
                    })
                }
            }
        ).show()


        handler.postDelayed({ InputMethodUtils.show(editText, context) }, 200)
    }

}